from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from model import db, StudentCourseNotice, CourseNotice,StudentCourse
from views.user import student_required,admin_required,assistant_required

notice_bp = Blueprint('notice', __name__)


# 获取学生未读通知的数量
# 获取学生未读通知的数量
@notice_bp.route('/unread_count/<student_id>', methods=['GET'])
@jwt_required()
def get_unread_count(student_id):

    current_user_id = get_jwt_identity()
    if current_user_id['uid'] != student_id:
        return jsonify({'msg': '无权限操作'}), 403

    # 从 student_course 表中查询该学生参与的课程 ID
    student_courses = db.session.query(StudentCourse.course_id).filter_by(student_id=student_id).distinct().all()
    course_ids = [course.course_id for course in student_courses]

    if not course_ids:
        return jsonify({'total_notifications': 0, 'unread_count': 0, 'read_count': 0}), 200

    # 查询课程通知表中这些课程的通知总数
    total_notifications = CourseNotice.query.filter(CourseNotice.course_id.in_(course_ids)).count()

    # 查询该学生的未读通知数量
    unread_count = StudentCourseNotice.query.filter_by(student_id=student_id, is_read=True).count()

    # 计算已读通知数量
    unread_count = total_notifications - unread_count

    return jsonify({
        'total_notifications': total_notifications,
        'unread_count': unread_count,
    }), 200


# 获取学生在某课程中的通知列表
@notice_bp.route('/list/<student_id>/<course_id>', methods=['GET'])
@jwt_required()
def get_notification_list(student_id, course_id):
    current_user_id = get_jwt_identity()['uid']
    if current_user_id != student_id:
        return jsonify({'msg': '无权限操作'}), 403

    # 查询该课程的所有通知
    notices = db.session.query(CourseNotice, StudentCourseNotice).outerjoin(
        StudentCourseNotice,
        (StudentCourseNotice.notice_id == CourseNotice.notice_id) & (StudentCourseNotice.student_id == student_id)
    ).filter(CourseNotice.course_id == course_id).all()

    notification_list = [{
        'notice_id': notice.CourseNotice.notice_id,
        'title': notice.CourseNotice.notice_title,
        'content': notice.CourseNotice.notice_content,
        'is_read': notice.StudentCourseNotice.is_read if notice.StudentCourseNotice else False,
        'timestamp': notice.CourseNotice.notice_time.isoformat()
    } for notice in notices]

    return jsonify({'notifications': notification_list}), 200


# 查看通知详情并标记为已读
@notice_bp.route('/detail/<student_id>/<notice_id>', methods=['GET'])
@jwt_required()
@student_required
def get_notification_detail(student_id, notice_id):
    current_user_id = get_jwt_identity()['uid']
    if current_user_id != student_id:
        return jsonify({'msg': '无权限操作'}), 403

    # 查询指定通知
    notice = CourseNotice.query.filter_by(notice_id=notice_id).first()

    if not notice:
        return jsonify({'msg': '通知不存在'}), 404

    # 将该通知标记为已读
    student_notice = StudentCourseNotice.query.filter_by(notice_id=notice_id, student_id=student_id).first()
    if not student_notice:
        student_notice = StudentCourseNotice(
            student_id=student_id,
            notice_id=notice_id,
            is_read=True,
            read_time=datetime.utcnow()
        )
        db.session.add(student_notice)
    else:
        student_notice.is_read = True
        student_notice.read_time = datetime.utcnow()

    db.session.commit()

    return jsonify({
        'notice_id': notice.notice_id,
        'title': notice.notice_title,
        'content': notice.notice_content,
        'timestamp': notice.notice_time.isoformat(),
        'is_read': True
    }), 200


# 老师发布新通知
@notice_bp.route('/publish/<teacher_id>/<course_id>', methods=['POST'])
@jwt_required()
@admin_required
def publish_notification(teacher_id, course_id):
    current_user_id = get_jwt_identity()['uid']
    if current_user_id != teacher_id:
        return jsonify({'msg': '无权限操作'}), 403

    data = request.json
    title = data.get('title')
    content = data.get('content')

    if not title or not content:
        return jsonify({'msg': '缺少必填项'}), 400

    # 创建新的课程通知
    new_notice = CourseNotice(
        teacher_id=teacher_id,
        course_id=course_id,
        notice_title=title,
        notice_content=content,
        notice_time = datetime.now()
    )

    db.session.add(new_notice)
    db.session.commit()

    return jsonify({'msg': '通知发布成功', 'notice_id': new_notice.notice_id}), 201


# 老师删除通知
@notice_bp.route('/delete/<teacher_id>/<course_id>/<notice_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_notification(teacher_id, course_id, notice_id):
    current_user_id = get_jwt_identity()['uid']
    if current_user_id != teacher_id:
        return jsonify({'msg': '无权限操作'}), 403

    # 查询该通知是否存在并且属于当前老师和课程
    notice = CourseNotice.query.filter_by(notice_id=notice_id, course_id=course_id, teacher_id=teacher_id).first()

    if not notice:
        return jsonify({'msg': '通知不存在或权限不足'}), 404

    # 删除与通知关联的学生通知记录
    StudentCourseNotice.query.filter_by(notice_id=notice_id).delete()

    # 删除通知本身
    db.session.delete(notice)
    db.session.commit()

    return jsonify({'msg': '通知删除成功'}), 200


# 老师查看通知详情
@notice_bp.route('/teacher/detail/<teacher_id>/<notice_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_teacher_notification_detail(teacher_id, notice_id):
    current_user_id = get_jwt_identity()['uid']
    if current_user_id != teacher_id:
        return jsonify({'msg': '无权限操作'}), 403

    # 查询指定通知，确保通知由当前老师发布
    notice = CourseNotice.query.filter_by(notice_id=notice_id, teacher_id=teacher_id).first()

    if not notice:
        return jsonify({'msg': '通知不存在或无权限查看'}), 404

    return jsonify({
        'notice_id': notice.notice_id,
        'title': notice.notice_title,
        'content': notice.notice_content,
        'timestamp': notice.notice_time.isoformat()
    }), 200
